package com.ramos.kuaixiao.network;

import android.os.AsyncTask;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.db.StoreNumDB;
import com.ramos.kuaixiao.entity.FirstWarehouse;
import com.ramos.kuaixiao.utils.CommUtil;
import com.ramos.kuaixiao.utils.FileUtil;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;

public class DownloadStoreNumTask extends AsyncTask<Void, Integer, Boolean> {
    private final static String TAG = "DownloadStoreNum";
    private int type;

    public DownloadStoreNumTask(int i) {
        type = i;
    }

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            //获取所有库存数据
            //getAllStoreNum();
            getAllLocalStoreNum();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    private void getAllLocalStoreNum() {
        File file = new File(FileUtil.getDataPath(App.mContext) + "/tbl_stock.csv");
        List<FirstWarehouse> list = readStoreNumCsv(file.getAbsolutePath());
        CommUtil.d(App.mContext,TAG, "tbl_stock:" + list.size());
        StoreNumDB customerDB = new StoreNumDB();
        customerDB.addAllStoreNum(list);
    }

    private List<FirstWarehouse> readStoreNumCsv(String absolutePath) {
        List<FirstWarehouse> readerArr = new ArrayList<>();
        Scanner in = Utils.readCsv(absolutePath);
        try {
            in.nextLine();
            while (in.hasNextLine()) {
                String s = in.nextLine();
                String[] lines = s.split(",");
              /*  Log.e(TAG, "tbl_stock:" + Utils.replaceStr(lines[0]) + " "+ Utils.replaceStr(lines[8]) + " " + Utils.replaceStr(lines[5]) + " "  +Utils.replaceStr(lines[6])
                            + " "  + Integer.valueOf(Utils.replaceStr(lines[11])) + " "  + (Integer.valueOf(Utils.replaceStr(lines[11])) - Integer.valueOf(Utils.replaceStr(lines[13]))) + " "  + Integer.valueOf(Utils.replaceStr(lines[13])) + " "  + Integer.valueOf(Utils.replaceStr(lines[10])));*/
                FirstWarehouse bean = new FirstWarehouse(Utils.replaceStr(lines[0]),Utils.replaceStr(lines[8]), Utils.replaceStr(lines[5]), Utils.replaceStr(lines[6])
                        , Integer.valueOf(Utils.replaceStr(lines[11])), (Integer.valueOf(Utils.replaceStr(lines[11])) - Integer.valueOf(Utils.replaceStr(lines[13]))), Integer.valueOf(Utils.replaceStr(lines[13])), Integer.valueOf(Utils.replaceStr(lines[10])), Long.valueOf(Utils.replaceStr(lines[16])));
                readerArr.add(bean);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return readerArr;
    }

    private Long getlong(String s) {
        BigDecimal bd = new BigDecimal(s);
        String str = bd.toPlainString();
        return Long.valueOf(str);
    }

    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }


    @Override
    protected void onProgressUpdate(Integer... values) {

    }

    @Override
    protected void onPostExecute(Boolean result) {

    }

    private void getAllStoreNum() {
        try {
            String url = NetUtils.PRODUCT_WAREHOUSE;
            long time = 0;
            if (SharedPreference.getPreferInteger("isFirstLogin") == 1) {
                time = new StoreNumDB().getMaxModifyTime();
            }
            String path = url + SharedPreference.getPreferString("dealer") + "&modifyTime=" + time;
            Log.e(TAG, "PRODUCT_WAREHOUSE：path=" + path);
            SyncHttpClient client = new SyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(120000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        JSONObject jsonObejct = JSONObject.parseObject(result);
                        Log.e(TAG, "PRODUCT_WAREHOUSE:result=" + result);
                        if (jsonObejct.getInteger("status") == 200) {
                            JSONObject data = jsonObejct.getJSONObject("data");
                            StringBuilder stringBuilder = new StringBuilder();
                            stringBuilder.append(data.getJSONArray("rows").toString());
                            List<FirstWarehouse> customerList = JSONArray.parseArray(stringBuilder.toString(), FirstWarehouse.class);
                            if (customerList != null && customerList.size() > 0) {
                                Log.e(TAG, "PRODUCT_WAREHOUSE:mCustomerList=" + customerList.size());
                                StoreNumDB customerDB = new StoreNumDB();
                                //customerDB.addAllStoreNum(customerList);
                                if (SharedPreference.getPreferInteger("isFirstLogin") == 0) {
                                    customerDB.addAllStoreNum(customerList);
                                } else {
                                    //customerList = customerDB.findAllStoreNum();
                                    customerDB.updateAllStoreNum(customerList);
                                }
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
